package com.hdl.script.ui.adapter

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import com.hdl.script.R
import com.hdl.script.logic.autojs.AccessibilityServiceTool
import com.hdl.script.logic.launch.AssetsProjectLauncher
import com.hdl.script.logic.launch.GlobalProjectLauncher
import com.hdl.script.model.CommonViewHolder
import com.hdl.script.model.Script
import com.hdl.script.ui.activity.ScriptRecyclerActivity
import com.stardust.app.GlobalAppContext
import com.stardust.autojs.core.accessibility.AccessibilityService
import com.stardust.autojs.execution.ScriptExecution
import com.stardust.autojs.execution.ScriptExecutionListener
import com.stardust.view.accessibility.AccessibilityServiceUtils

class ScriptAdapter(context: Context) : CommonRecyclerAdapter<Script>(context), View.OnClickListener {

    override fun convert(holder: CommonViewHolder, item: Script, position: Int) {
        val textDesc = holder.itemView.findViewById<AppCompatTextView?>(R.id.textDesc)
        textDesc?.text = "描述：${item.name}"
        val textMain = holder.itemView.findViewById<AppCompatTextView?>(R.id.textMain)
        textMain?.text = "脚本文件名：${item.path}/${item.main}"
        val textVersion = holder.itemView.findViewById<AppCompatTextView?>(R.id.textVersion)
        textVersion?.text = "版本号：${item.versionName}(${item.versionCode})"
        val btnRun = holder.itemView.findViewById<View?>(R.id.btnRun)
        btnRun?.tag = item
        btnRun?.setOnClickListener(this)
    }

    override fun getItemViewType(position: Int): Int {
        return R.layout.view_script_item
    }

    override fun onClick(v: View?) {
        val obj = v?.tag
        if (obj is Script) {
            if (AccessibilityServiceUtils.isAccessibilityServiceEnabled(context, AccessibilityService::class.java)) {
                AssetsProjectLauncher(obj.path, GlobalAppContext.get()).runScript(object : ScriptExecutionListener {
                    override fun onStart(execution: ScriptExecution?) {
                    }

                    override fun onSuccess(execution: ScriptExecution?, result: Any?) {
                    }

                    override fun onException(execution: ScriptExecution?, e: Throwable?) {
                    }
                })
            } else {
                AccessibilityServiceTool.goToAccessibilitySetting()
            }
        }
    }
}